package com.github.m6d21.sso.service.role.impl;

import com.github.m6d21.sso.core.exception.BusinessException;
import com.github.m6d21.sso.dao.role.dao.IRoleDao;
import com.github.m6d21.sso.model.role.entity.Role;
import com.github.m6d21.sso.model.role.qo.RoleQO;
import com.github.m6d21.sso.service.role.IRoleService;
import com.github.m6d21.sso.support.enums.StatusCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.List;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import org.springframework.stereotype.Service;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/1/4 Fri 17:19:00
 * @since 1.0.0
 */
@Service("roleService")
public class RoleServiceImpl implements IRoleService {

    @Resource
    private IRoleDao roleDao;

    private static final int DEFAULT_PAGE_NO = 1;
    private static final int DEFAULT_PAGE_SIZE = 20;

    @Override
    public PageInfo<Role> queryByPage(Integer pageNo, Integer pageSize, RoleQO roleQO) {
        pageNo = (pageNo == null ? DEFAULT_PAGE_NO : pageNo);
        pageSize = (pageSize == null ? DEFAULT_PAGE_SIZE : pageSize);
        PageHelper.startPage(pageNo, pageSize);
        List<Role> list = roleDao.query(roleQO);
        return PageInfo.of(list);
    }

    @Override
    public PageInfo<Role> queryByPageForAdmin(Integer pageNo, Integer pageSize, RoleQO roleQO) {
        pageNo = (pageNo == null ? DEFAULT_PAGE_NO : pageNo);
        pageSize = (pageSize == null ? DEFAULT_PAGE_SIZE : pageSize);
        PageHelper.startPage(pageNo, pageSize);
        List<Role> list = roleDao.queryForAdmin(roleQO);
        return PageInfo.of(list);
    }

    @Override
    public Role saveRole(Role role) {
        boolean success = roleDao.insertSelectiveRole(role);
        if (!success) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "保存权限失败");
        }
        return role;
    }

    @Override
    public Role modifyRoleById(Role role) {
        boolean success = roleDao.updateSelectiveRoleById(role);
        if (!success) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "更新权限失败");
        }
        return role;
    }

    @Override
    public Boolean deleteRoleById(@NotNull(message = "权限id不能为空") Integer id) {
        return roleDao.deleteById(id);
    }

    @Override
    public Boolean deleteRoleByIds(@NotNull(message = "权限ids不能为空") List<Integer> ids) {
        return roleDao.deleteByIds(ids);
    }

    @Override
    public Boolean existByRoleCode(@NotNull(message = "权限Code不能为空") String roleCode) {
        RoleQO roleQO = new RoleQO();
        roleQO.setRoleCode(roleCode);
        List<Role> list = roleDao.find(roleQO);
        if (list != null && list.size() > 0) {
            return true;
        }
        return false;
    }
}
